package com.aid.winter.controller;

import com.aid.winter.common.response.Result;
import com.aid.winter.dto.request.ApplicationCreateRequest;
import com.aid.winter.dto.request.ApplicationAuditRequest;
import com.aid.winter.dto.response.ApplicationVO;
import com.aid.winter.dto.response.PageResult;
import com.aid.winter.service.AidApplicationService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import cn.dev33.satoken.stp.StpUtil;
import com.aid.winter.common.annotation.RequiredRole;
import com.aid.winter.common.constant.RoleConstants;
import com.aid.winter.common.exception.BusinessException;
import com.aid.winter.service.SysUserService;
import com.aid.winter.entity.SysUser;

/**
 * 补助申请管理控制器
 */
@RestController
@RequestMapping("/application")
@RequiredArgsConstructor
public class AidApplicationController {

    private final AidApplicationService applicationService;
    private final SysUserService userService;

    /**
     * 创建申请（仅学生可操作）
     */
    @PostMapping
    @RequiredRole(1)
    public Result<ApplicationVO> createApplication(@Validated @RequestBody ApplicationCreateRequest request) {
        Long studentId = StpUtil.getLoginIdAsLong();
        
        SysUser student = userService.getUserById(studentId);
        if (!request.getStudentNo().equals(student.getStudentId()) || 
            !request.getStudentName().equals(student.getRealName())) {
            throw new BusinessException("学生信息不匹配");
        }
        
        return Result.ok(applicationService.createApplication(studentId, request));
    }

    /**
     * 分页查询申请列表（所有角色可查看，但权限不同）
     */
    @GetMapping("/list")
    public Result<PageResult<ApplicationVO>> listApplications(
            @RequestParam(required = false) Long batchId,
            @RequestParam(required = false) Long studentId,
            @RequestParam(required = false) Integer status,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        // 学生只能查看自己的申请
        if (StpUtil.hasRole(RoleConstants.ROLE_PREFIX + RoleConstants.ROLE_STUDENT)) {
            studentId = StpUtil.getLoginIdAsLong();
        }
        return Result.ok(applicationService.listApplications(batchId, studentId, status, pageNum, pageSize));
    }

    /**
     * 获取申请详情
     *
     * @param id 申请ID
     * @return 申请详细信息
     */
    @GetMapping("/{id}")
    public Result<ApplicationVO> getApplicationDetail(@PathVariable Long id) {
        return Result.ok(applicationService.getApplicationDetail(id));
    }

    /**
     * 更新申请（仅学生可操作自己的申请）
     */
    @PutMapping("/{id}")
    @RequiredRole(1)
    public Result<ApplicationVO> updateApplication(
            @PathVariable Long id,
            @Validated @RequestBody ApplicationCreateRequest request) {
        Long studentId = StpUtil.getLoginIdAsLong();
        return Result.ok(applicationService.updateApplication(id, studentId, request));
    }

    /**
     * 审核申请（辅导员、学院、学校用户可操作）
     */
    @PostMapping("/{id}/audit")
    @RequiredRole({2, 3, 4})
    public Result<Void> auditApplication(
            @PathVariable Long id,
            @RequestParam Integer auditLevel,
            @Validated @RequestBody ApplicationAuditRequest request) {
        // 验证审核层级与角色是否匹配
        Integer roleType = StpUtil.getSession().getInt("roleType");
        if (!auditLevel.equals(roleType)) {
            throw new BusinessException("无权进行该层级的审核");
        }
        
        Long auditorId = StpUtil.getLoginIdAsLong();
        applicationService.auditApplication(id, auditorId, auditLevel, request);
        return Result.ok();
    }

    /**
     * 批量审核申请（辅导员、学院、学校用户可操作）
     */
    @PostMapping("/batch-audit")
    @RequiredRole({2, 3, 4})
    public Result<Void> batchAuditApplications(
            @RequestParam Long[] ids,
            @RequestParam Integer auditLevel,
            @Validated @RequestBody ApplicationAuditRequest request) {
        // 验证审核层级与角色是否匹配
        Integer roleType = StpUtil.getSession().getInt("roleType");
        if (!auditLevel.equals(roleType)) {
            throw new BusinessException("无权进行该层级的审核");
        }
        
        Long auditorId = StpUtil.getLoginIdAsLong();
        applicationService.batchAuditApplications(ids, auditorId, auditLevel, request);
        return Result.ok();
    }
} 